package com.fly.lambda.framework.web.session.Impl;

import com.alibaba.fastjson.JSONObject;
import com.fly.lambda.framework.utils.CommonUtils;
import com.fly.lambda.framework.utils.CookieUtil;
import com.fly.lambda.framework.web.session.AccountSession;
import com.fly.lambda.framework.web.session.SessionManage;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Fly on 2016/7/19.
 */
public class SessionManageImpl implements SessionManage{

    public String setAccountSession(HttpServletResponse response, AccountSession accountSession) {
        String sessionId = CommonUtils.genPK(); //生成cookie名称
        String value = JSONObject.toJSONString(accountSession);
        CookieUtil.writeCookie(response, COOKIE_SESSION_NAME, value);
        return sessionId;
    }

    public AccountSession getAccountSession(HttpServletRequest request) {
        AccountSession accountSession = null;
        String value = CookieUtil.readCookie(request, COOKIE_SESSION_NAME);
        if (StringUtils.isNotBlank(value)){
            accountSession = JSONObject.parseObject(value, AccountSession.class);
        }
        return accountSession;
    }

    public void updateAccountSession(HttpServletResponse response, String sessionId) {

    }

    public void removeAccountSession(HttpServletResponse response) {
        CookieUtil.removeCookie(response, COOKIE_SESSION_NAME);
    }
}
